package cluster

import (
	"gomod.alauda.cn/mysql-mgr-operator/pkg/constant"
	"time"
)

type StopOption struct {
}

type Stop struct {
	*StopOption
	*Base
}

func NewStop(opt *StopOption) *Stop {
	return &Stop{
		StopOption: opt,
	}
}

func (r *Stop) WithBase(base *Base) *Stop {
	r.Base = base
	return r
}

func (r *Stop) Run() error {
	switch r.Type {
	case TypeMysql:
		return r.stopMysql()
	case TypeMgr:
		return r.stopMgr()
	default:
		err := r.stopMysql()
		if err != nil {
			return r.stopMgr()
		}
	}
	return nil
}

func (r *Stop) stopMysql() error {
	cr, err := r.getMysqlCr()
	if err != nil {
		return err
	}
	now := time.Now().Format(time.RFC3339)
	cr.Annotations[constant.MgrStop] = now
	err = r.update(cr)
	if err != nil {
		return err
	}
	return nil
}

func (r *Stop) stopMgr() error {
	cr, err := r.getMgrCr()
	if err != nil {
		return err
	}
	now := time.Now().Format(time.RFC3339)
	cr.Annotations[constant.MgrStop] = now
	err = r.update(cr)
	if err != nil {
		return err
	}
	return nil
}
